import logging
from logging.handlers import RotatingFileHandler

import redis
from flask import Flask,session
from flask_session import Session
from flask_sqlalchemy import SQLAlchemy
from flask_wtf import CSRFProtect
from flask_wtf.csrf import generate_csrf
from config import config_dict


#定义redis_store
from info.utils.commons import index_class

redis_store =None
#定义db
db = SQLAlchemy()
def create_app(config_name):

	app = Flask(__name__)
	config = config_dict.get(config_name)

	log_file(config.LEVEL)

	app.config.from_object(config)

	#创建SQLAlchemy
	# db = SQLAlchemy(app) #等价于 db=SQLAlchemy(), db.init_app(app)
	db.init_app(app)

	#创建redis对象
	global redis_store
	redis_store = redis.StrictRedis(host=config.REDIS_HOST,port=config.REDIS_PORT,decode_responses=True)

	CSRFProtect(app)
	Session(app)
	#将首页蓝图对象index_blu 注册到app
	from info.modules.index import index_blu
	app.register_blueprint(index_blu)
	#将认证蓝图对象passpor_blue注册到app中
	from info.modules.passport import passport_blue
	app.register_blueprint(passport_blue)
	#将新闻蓝图对象new_blue注册到app中
	from info.modules.news import news_blue
	app.register_blueprint(news_blue)
	# 将用户蓝图对象user_blue注册到app中
	from info.modules.user import user_blue
	app.register_blueprint(user_blue)

	# 将过滤器，添加到默认过滤器列表中
	app.add_template_filter(index_class,"index_class")

	#使用请求钩子，after_request拦截所有响应
	@app.after_request
	def after_request(resp):
		value = generate_csrf()
		resp.set_cookie("csrf_token",value)
		return resp

	print(app.url_map)
	return app
def log_file(LEVEL):
	logging.basicConfig(level=LEVEL)
	file_log_handler = RotatingFileHandler("logs/log",maxBytes=1024*1024*1024,backupCount=10)
	formatter = logging.Formatter('%(levelname)s %(filename)s:%(lineno)d %(message)s')
	file_log_handler.setFormatter(formatter)
	logging.getLogger().addHandler(file_log_handler)